#-*- coding: utf-8 -*-
import socket
import sys
#from thread import *

class Tcpserver(object):
    serverDict = {}
    def __init__(self, port):
        self.host = ''
        self.port = port
        self._serverDict = {}
        self._clientmsg = {}

    def getServerDic(self):
        return self._serverDict
    def getClientmsg(self):
        return self._clientmsg
    def getAllClentIp(self):
        return self._serverDict.keys()

    def serverInit(self):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print 'Socket created'

        # Bind socket to local host and port
        try:
            server.bind((self.host, self.port))
        except socket.error, msg:
            print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
            sys.exit()

        print 'Socket bind complete'

        # Start listening on socket
        server.listen(10)
        print 'Socket now listening'
        while True:
            conn, addr = server.accept()
            print 'Connected with ' + addr[0] + ':' + str(addr[1])
            print conn
            self._serverDict[addr[0]] = conn
            print self._serverDict.items()
            #start_new_thread(clientthread, (conn, addr,))
            t1 = threading.Thread(target=self.clientthread, name='thread1', args=(addr, conn,))
            t1.start();

    def clientthread(self, addr,conn):
        while True:
            data = conn.recv(512) #与recv()类似,返回值是（data,address）。其中data是包含接收数据的字符串，address是发送数据的套接字地址。
            print "data:"+ str(data) +',address:'+ str(addr)
            self._clientmsg[addr[0]] = str(data)
            reply = 'OK...\n'
            #+ str(data) + ',address:'+ str(addr) + '\n'
            if data:
                conn.sendall(reply)
                #conn.sendall("FFF001\n")
        conn.close()

    def sendclientCmd(self, addr, cmd):
        print addr
        conn = self._serverDict.get(addr)
        print conn,cmd
        if conn:
            conn.sendall(cmd)

# now keep talking with the client
if __name__ =='__main__':
    server = Tcpserver(9000)
    threading.Thread(target=server.serverInit, name='main').start()
    while True:
        server.sendclientCmd('192.168.1.111', 'FFF0001\n')
        dic = server.getClientmsg()
        print dic
    server.close()